package com.xjoyt.pay.master.services;

import java.lang.reflect.Field;
import java.util.Map.Entry;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.master.po.Distributor;
import com.xjoyt.pay.master.po.DistributorPreference;
import com.xjoyt.pay.master.po.Merchant;
import com.xjoyt.pay.master.repository.DistributorPreferenceRepository;
import com.xjoyt.pay.master.repository.DistributorRepository;
import com.xjoyt.pay.master.repository.MerchantRepository;

@Service
public class DistributorPreferenceService extends AbstractService {

	@Autowired
	private DistributorPreferenceRepository repository;

	@Autowired
	private DistributorRepository distributorRepository;

	@Autowired
	private MerchantRepository merchantRepository;

	public DistributorPreference get(String id) {
		return repository.findOne(id);
	}

	public DistributorPreference getByNo(String no) {
		return repository.findOneByNo(no);
	}

	public ExecuteResult<DistributorPreference> save(DistributorPreference entity) {
		if (StringUtils.isBlank(entity.id)) {
			return ExecuteResult.fail("商户不能为空");
		}

		Merchant merchant = merchantRepository.findOne(entity.id);
		if (merchant == null) {
			return ExecuteResult.fail("商户不存在");
		}
		repository.create(entity);
		return null;
	}

	public ExecuteResult<?> saveValue(String id, Entry<String, String> param) throws Exception {
		if ("id".equals(param.getKey())) {
			return ExecuteResult.fail("无法修改id");
		}
		DistributorPreference entity = repository.findOne(id);
		if (entity == null) {
			Distributor distributor = distributorRepository.findOne(id);
			if (distributor == null)
				return ExecuteResult.fail("数据不存在");
			entity = new DistributorPreference();
			entity.id = distributor.id;
			entity.distributor = distributor;
		}

		Field field = entity.getClass().getField(param.getKey());
		Object convert = ConvertUtils.convert(param.getValue(), field.getType());
		field.set(entity, convert);
		repository.save(entity);
		return ExecuteResult.ok();
	}
}
